# coding = utf-8
import requests
from django.core.cache import cache
from django.db.models import Q
from rest_framework import status
from rest_framework.generics import ListAPIView, CreateAPIView, RetrieveAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

from base.base import MyModelViewSet
from rooms.api.authentication import JSONWebTokenVideoAuthentication
from rooms.api.serializers import RoomSerializer, VideoUserInfoSerializer, RoomCodeSerializer, VideoLoginUserSerializer
from rooms.api.utils import jwt_payload_handler, jwt_encode_handler, jwt_response_payload_handler
from rooms.models import Room, VideoUserInfo, VideoLoginUser


class RoomListAPIView(ListAPIView):
    """会议室列表"""
    authentication_classes = ()
    permission_classes = ()
    pagination_class = None
    queryset = Room.objects.filter(status=1)
    serializer_class = RoomCodeSerializer


class RoomViewSet(MyModelViewSet):
    # authentication_classes = ()
    permission_classes = ()
    queryset = Room.objects.all()
    serializer_class = RoomSerializer

    def get_queryset(self):
        queryset = super().get_queryset()
        name = self.request.query_params.get("name")
        if name:
            queryset = queryset.filter(description__contains=name)

        return queryset


class VideoLoginUserViewSet(MyModelViewSet):
    # authentication_classes = ()
    permission_classes = ()
    queryset = VideoLoginUser.objects.all()
    serializer_class = VideoLoginUserSerializer

    def get_queryset(self):
        queryset = super().get_queryset()
        name = self.request.query_params.get("name")
        if name:
            queryset = queryset.filter(Q(real_name__contains=name)
                                       | Q(name__contains=name)
                                       | Q(telephone__contains=name))

        return queryset


class VideoUserInfoViewSet(MyModelViewSet):
    # authentication_classes = ()
    permission_classes = ()
    queryset = VideoUserInfo.objects.all()
    serializer_class = VideoUserInfoSerializer

    def get_queryset(self):
        queryset = super().get_queryset()
        name = self.request.query_params.get("name")
        if name:
            queryset = queryset.filter(Q(openid__contains=name)
                                       | Q(name__contains=name)
                                       | Q(nickname__contains=name) | Q(telephone__contains=name))

        return queryset


class RecordVideoUser(CreateAPIView):
    """记录用户视频登录"""
    authentication_classes = ()
    permission_classes = ()
    serializer_class = VideoUserInfoSerializer
    queryset = VideoUserInfo.objects.all()

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)

        user = serializer.data
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        res_data = jwt_response_payload_handler(token, user)
        cache.set(user.get("openid"), token, 24 * 3600)
        headers = self.get_success_headers(serializer.data)
        return Response(res_data, status=status.HTTP_201_CREATED, headers=headers)


class VideoRoomRetrieveAPIView(RetrieveAPIView):
    """获取指定会议室信息"""
    authentication_classes = (JSONWebTokenVideoAuthentication,)
    permission_classes = ()
    serializer_class = RoomCodeSerializer
    queryset = Room.objects.filter(status=1)


class WeChatUserLoginQrCode(APIView):
    """微信扫码登录"""
    authentication_classes = ()
    permission_classes = ()
    HEADERS = {'content-type': 'application/json;charset=utf-8'}
    url = 'http://wx.xzls.vip/api/wechat/user_login_qrcode/'

    def post(self, request):
        try:
            r = requests.post(self.url, headers=self.HEADERS)
            r.raise_for_status()
            return Response(r.json())
        except requests.RequestException as e:
            res = dict()
            res["error_code"] = 500
            res["message"] = str(e)
            return Response(res)


class WeChatUserLoginQrCodInfo(APIView):
    """微信扫码查询登录信息"""
    authentication_classes = ()
    permission_classes = ()
    HEADERS = {'content-type': 'application/json;charset=utf-8'}
    url = 'http://wx.xzls.vip/api/wechat/video_user_info/'

    def get(self, request):
        room = request.query_params.get("room", None)

        try:
            params = {
                "room": room
            }
            r = requests.get(self.url, params=params, headers=self.HEADERS)
            r.raise_for_status()
            return Response(r.json())
        except requests.RequestException as e:
            res = dict()
            res["error_code"] = 500
            res["message"] = str(e)
            return Response(res)

